<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import service from '@/utils/request'
import { ElMessage } from 'element-plus'
import EZUIKit from 'ezuikit-js'

const videoUrl = ref('ezopen://open.ys7.com/AB9831171/1.live')
const isLoading = ref(true)
const hasError = ref(false)
const player = ref(null)
const deviceNumber = ref('AB9831171')
const accessToken = ref('')

// 添加emit定义
const emit = defineEmits(['capture-success'])

// 初始化视频播放器
const initVideoPlayer = async () => {
  try {
    isLoading.value = true
    hasError.value = false

    // 获取萤石云token
    const { data } = await service.post('/api/cameras/token')
    if (!data?.accessToken) {
      throw new Error('获取Token失败')
    }
    accessToken.value = data.accessToken // 保存token供抓拍使用
    console.log('获取Token成功:', data.accessToken)

    // 获取容器尺寸
    const container = document.getElementById('video-container')
    const width = container.clientWidth
    const height = container.clientHeight
    console.log('容器尺寸:', width, height)

    // 初始化播放器
    player.value = new EZUIKit.EZUIKitPlayer({
      id: 'video-player',
      width: width,
      height: height,
      template: 'simple',
      url: videoUrl.value,
      accessToken: data.accessToken,
      autoplay: true,
      handleError: (e) => {
        console.error('播放器错误:', e)
        hasError.value = true
        ElMessage.error('视频加载失败')
      },
      handleSuccess: () => {
        console.log('播放成功')
        isLoading.value = false
      },
      handleFirstFrameDisplay: () => {
        console.log('首帧画面显示')
      }
    })

  } catch (error) {
    console.error('初始化视频播放器失败:', error)
    hasError.value = true
    isLoading.value = false
    ElMessage.error(error.message || '视频初始化失败')
  }
}

// 销毁播放器
const destroyPlayer = () => {
  if (player.value) {
    try {
      player.value.destroy()
    } catch (error) {
      console.error('销毁播放器失败:', error)
    }
    player.value = null
  }
}

// 抓拍功能
const handleCapture = async () => {
  try {
    if (!accessToken.value) {
      ElMessage.error('Token无效，请刷新页面重试')
      return
    }

    const { data } = await service.post(
        `/api/cameras/${deviceNumber.value}/capture`,
        null,
        {
          params: {
            accessToken: accessToken.value
          }
        }
    )

    if (data?.picUrl) {
      ElMessage.success('抓拍成功')
      // 触发刷新事件
      emit('capture-success')
    } else {
      throw new Error('抓拍失败，未获取到图片URL')
    }
  } catch (error) {
    console.error('抓拍失败:', error)
    ElMessage.error(error.message || '抓拍失败')
  }
}

onMounted(() => {
  initVideoPlayer()
})

onBeforeUnmount(() => {
  destroyPlayer()
})
</script>

<template>
  <div class="panel">
    <div class="panel-header">
      <span>实时监控</span>
      <div class="controls" v-if="!isLoading && !hasError">
        <el-button-group>
          <el-button
              size="small"
              type="primary"
              @click="handleCapture"
              :loading="isLoading"
          >
            <el-icon><Camera /></el-icon>
            抓拍
          </el-button>
        </el-button-group>
      </div>
    </div>

    <div id="video-container" class="video-container">
      <template v-if="isLoading">
        <div class="video-placeholder">
          <el-icon class="loading"><Loading /></el-icon>
          <div>加载中...</div>
        </div>
      </template>
      <template v-else-if="hasError">
        <div class="video-placeholder error">
          <el-icon><VideoCameraFilled /></el-icon>
          <div class="placeholder-text">视频加载失败</div>
        </div>
      </template>
      <div id="video-player" class="video-player"></div>
    </div>
  </div>
</template>

<style scoped>
.panel {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.panel-header {
  flex-shrink: 0;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
}

.video-container {
  flex: 1;
  position: relative;
  background: rgba(0,0,0,0.5);
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-player {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 确保视频画面居中且保持比例 */
:deep(.ezuikit-video),
:deep(.video-js) {
  width: 100% !important;
  height: 100% !important;
  background: transparent !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

:deep(.ezuikit-video video),
:deep(.video-js video) {
  object-fit: contain !important;
  max-width: 100% !important;
  max-height: 100% !important;
}

.video-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
  gap: 10px;
}

.loading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.controls {
  display: flex;
  gap: 10px;
}

.error {
  color: #f56c6c;
}
</style> 